
<template>
  <!--  -->
  <el-button
    type="primary"
    v-if="
      route.query.name === '1' ||
      route.query.name === '2' ||
      (route.query.name === '3' && route.path === '/myProject/approval/edit')
    "
    link
    @click="setPeople"
    >添加成员</el-button
  >
  <el-dialog
    title="新增成员"
    v-model="detailsvisible"
    :before-close="handleClose"
    width="70%"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form :inline="true" :model="formInline">
      <el-form-item label="姓名">
        <el-input
          class="filter-item"
          v-model="formInline.nickName"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属部门">
        <el-cascader
          class="input-item"
          v-model="formInline.deptId"
          :clearable="true"
          placeholder="所属部门"
          :props="dropdownprops"
          :options="dropdownList"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24">
        <div class="table-wrapper">
          <el-table
            :data="tableData"
            style="width: 100%"
            header-cell-class-name="table-header-gray"
            v-loading="isShowloading"
          >
            <el-table-column
              type="index"
              align="center"
              width="55"
              label="序号"
            ></el-table-column>
            <el-table-column
              prop="nickName"
              align="center"
              label="姓名"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="phonenumber"
              align="center"
              label="手机号"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="dept.deptName"
              align="center"
              label="部门"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="postName"
              align="center"
              label="岗位"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="项目角色">
              <template #default="scope">
                <!-- {{1}} {{scope.row.projectRole}} -->
                <el-select
                  v-model="scope.row.projectRole"
                  placeholder="请选择"
                  @change="handelChange(scope.row)"
                >
                  <el-option
                    v-for="item in roleList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="120"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="selectTable(scope.row, scope.$index)"
                  v-if="!scope.row.check"
                  >选择</el-button
                >
                <el-button
                  link
                  type="danger"
                  @click="deleteTable(scope.row, scope.$index)"
                  v-if="scope.row.check"
                  >取消</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-size="pageSize"
            :page-sizes="[999999]"
            layout="total, prev, pager, next, sizes"
            :total="total"
          ></el-pagination>
        </el-row>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script  lang="ts" setup>
import { computed, ref, reactive, onMounted, watchEffect } from "vue";

//@ts-ignore
import { useEmpty } from "@/utils/index";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";

//@ts-ignore
import { deptNameApi, roleQuery } from "@/api/project/conversion";

import { Search } from "@element-plus/icons-vue";

import useUserStore from "@/store/modules/user";
//
const detailsvisible = ref(false);
const route = useRoute();

const formInline = reactive({
  nickName: "",
  deptId: "",
});
// 添加成员
const setPeople = () => {
  detailsvisible.value = true;
  //  console.log(props.projectUserDtoList, "-props.projectUserDtoList---");
  conversionRole();
};

const check = ref(true);
const userStore = useUserStore();

const tableData = ref([]);

const isShowloading = ref(false);

const roleList = ref([
  {
    id: "1",
    label: "主管领导",
  },
  {
    id: "2",
    label: "项目经理",
  },
  {
    id: "3",
    label: "项目助理",
  },
]);

const dropdownList = ref([]);

let dropdownprops = {
  value: "deptId",
  label: "deptName",
  emitPath: false,
};

// 所属部门名称
const deptNameRole = async () => {
  try {
    let params = {};
    const response = await deptNameApi(params);
    if (response.code === 200 && response.data.length >= 0) {
      dropdownList.value = response.data;
    }
  } catch (err) {
    console.log(err);
  }
};

let pageNum = ref(1);
let pageSize = ref(999999);
let total = ref(0);

const props = defineProps({
  projectUserDtoList: {
    type: Array,
    default: () => [],
  },
});

const handelChange = (value) => {
  if (value.userId === userStore.userId) {
    emit("handelChange", value);
  }
};

let nickName='';
let deptId='';
// 监听变化
watchEffect(async ()=>{
  nickName = formInline.nickName;
  deptId = formInline.deptId;
  onSubmit();
});


// 角色查询功能
const conversionRole = async () => {
  try {
    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...formInline,
    };

    const response = await roleQuery(params);
    if (response.code === 200 && response.rows.length >= 0) {
      tableData.value = response.rows
      total.value = Number(response.total);

      if (props.projectUserDtoList && props.projectUserDtoList.length) {

        // @ts-ignore
        const sameList = [];
        props.projectUserDtoList.forEach((user: any) => {
          const same = tableData.value.find((it) => user.userId === it.userId);
          if (same) {
            sameList.push(same);
            // 赋值名字 和状态
            same.check = true;
            same.projectRole = user.projectRole === 'null' ? '' : user.projectRole;
          }
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
};

let paramsSubmit;
// const onSubmit = (val) => {
//   conversionRole();
// };
const onSubmit = () => {
  conversionRole();
};

// 重置
const reset = () => {
  pageNum.value = 1;
  // pageSize.value = 99;
  formInline.deptId = "";
  formInline.nickName = "";
  conversionRole();
};

const emit = defineEmits([
  "selectTable",
  "deleteTable",
  "conversionRole",
  "handelChange",
]);

const userList = ref([]);

const rowTable = ref();
// 点击选择的时候
const selectTable = (row, index) => {
  // console.log(row.userId === userStore.userId, "---row---");

  //要先选择项目角色，没选进行提示

  if (row.userId !== userStore.userId && useEmpty(row.projectRole)) {
    ElMessage.error("请您先选择项目角色");
    return false;
  }

  row.check = true;
  rowTable.value = row;

  // 点击下拉框之后，得到数据,传到前面的表格里面
  emit("selectTable", rowTable.value);
};

// 点击弹窗
const handleClose = async () => {
  detailsvisible.value = false;
  await conversionRole();
  // if (childRef.value) {
  //   childRef.value.formInline.nickName = "";
  //   childRef.value.formInline.deptId = "";
  // }
};

// 点击删除
const deleteTable = (row, index) => {
  if (route.query.name === "1" && row.userId === userStore.userId) {
    row.check = true;
  } else {
    row.check = false;
    row.projectRole = "";
    row.projectRole = "";
    emit("deleteTable", row, index);
  }
};

const handleSizeChange = (valueSise) => {
  pageSize.value = valueSise;
  conversionRole();
};

const handleCurrentChange = (valuePage) => {
  pageNum.value = valuePage;
  conversionRole();
};
const currentPerson = ref();

onMounted(async () => {
  await deptNameRole();
  await conversionRole();
  // 默认当前选择人选择
  currentPerson.value = tableData.value.find(
    (it) => userStore.userId === it.userId
  );

  if (currentPerson.value) {
    currentPerson.value.check = true;
  }
});

// 暴露数据或方法给父组件
defineExpose({
  formInline,
  currentPerson,
});

// defineExpose({ tableData })
</script>
<style lang="scss" scoped>
.table-wrapper {
  height: 500px; /* 设置你需要的高度 */
  overflow: auto;
}
</style>
